package liu.de.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import liu.de.dto.MyTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author liude
 */
@Service
@Slf4j
public class TaskService {

    private final ObjectMapper objectMapper;


    public TaskService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @RabbitListener(queues = "task")
    public void onMessage(Message message, Channel channel) {
        try {
            MyTask myTask = objectMapper.readValue(message.getBody(), MyTask.class);
            log.info("task {}", myTask.getId());
            TimeUnit.SECONDS.sleep(myTask.getDurationInSeconds());
        } catch (Exception e) {
            log.error("", e);
        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("", e);
        }
    }
}
